#include<iostream>
#include<pthread.h>
#include<semaphore.h>
#include<unistd.h>
#include<vector>
using namespace std;

int cap=10;
sem_t data_sem;//数据信号量
sem_t space_sem;//空间信号量
//使用信号量sem和环形队列实现生产者消费者模型
int producer_num=0;
int consumer_num=0;
vector<int> ringqueue(cap);

void *producer(void *arg)
{
    for(;;)
    {
        sem_wait(&space_sem);//等待空间信号量 space_sem为0时阻塞
        ringqueue[producer_num]=*(int*)arg;//生产数据
        cout<<"生产者生产了"<<*(int*)arg<<"数据"<<endl;
        (*(int*)arg)++;
        producer_num++;//生产者下标加1 下次访问该下标的数据
        producer_num%=cap;//实现环形队列
        sem_post(&data_sem);//增加数据信号量 data_sem++
        sleep(1);
    }

}
void *consumer(void* arg)
{
    for(;;)
    {
        sem_wait(&data_sem);//等待数据信号量 data_sem为0时阻塞
        int data=ringqueue[consumer_num];//消费数据
        consumer_num++;//消费者下标加1 下次访问该下标的数据
        consumer_num%=cap;
        cout<<"消费者消费了"<<data<<"数据"<<endl;
        sem_post(&space_sem);
        sleep(1);
    }
}
int main()
{
    int data=0;
    sem_init(&data_sem,0,0);
    sem_init(&space_sem,0,cap);
    
    pthread_t p,c;
    pthread_create(&p,NULL,producer,&data);
    pthread_create(&c,NULL,consumer,nullptr);
    pthread_join(p,nullptr);
    pthread_join(c,nullptr);

    sem_destroy(&data_sem);
    sem_destroy(&space_sem);
    return 0;
}